const Router = require('koa-router');
import  Department  from "../lib/models/Department"
import { responseResult, responseError, ERROR, responseOK } from "../lib/common/result"
import { sequelize } from "../lib/common/initdb"
import { User } from "../lib/models/User";

const router = new Router();
console.log("-----begin users router--------")
router.get('/outapi/department/:id', async (ctx: any) => {
  let department = await Department.findByPk(ctx.request.params.id);
  if (!department) {
    responseError(ctx, ERROR.USERNAME, "用户不存在");
    return;
  }
  responseResult(ctx, department);
  return;
});

router.put('/outapi/department', async (ctx: any) => {
  if (!ctx.request.body || ctx.request.body.npwd === "") {
    responseError(ctx, ERROR.PARAM, "参数错误");
    return;
  }
  let dp = await Department.findByPk(ctx.request.body.un);
  if (!dp) {
    responseError(ctx, ERROR.USERNAME, "用户不存在");
    return;
  }
  dp.save()
  return;
});



router.delete('/outapi/department/:id', async (ctx: any) => {
  if (!ctx.body.params || !ctx.body.params.id) {
    responseError(ctx, ERROR.PARAM, "参数错误");
  } else {
    //Department.findOne
    let department = await Department.findByPk(ctx.body.params.id)
    if (department != null) {
      let users = department.findUsers()
      if (!users) {
        responseError(ctx, ERROR.DB, "部门下存在用户，不能删除。");
        return
      }
    }
    Department.destroy({ where: { dId: ctx.body.params.id } }).then(() => {
      responseOK(ctx);
    }).catch((err: any) => {
      responseError(ctx, ERROR.DB, err.toString());
    });
  }
  return;
});

router.put('/outapi/department/:id', async (ctx: any) => {
  let id = ctx.body.params.id
  if (!id) {
    responseError(ctx, ERROR.PARAM, "参数错误");
    return
  }
  let uid = ctx.body.query.uid
  if (!uid) {
    responseError(ctx, ERROR.PARAM, "参数错误");
    return
  }
  sequelize.transaction(void function (t: TransferFunction) {
    Department.findByPk(id).then((department:Department|null) => {
      if (department) {
        User.findByPk(uid).then((user) => {
          if (user == null) {
            throw "用户不存在";
          } else {
            user.departmentId = id
            user.save()
          }

        })
      } else {
        throw "部门不存在";
      }
    })
  }).then(() => {
    responseOK(ctx)
  }).catch(err => {
    responseError(ctx, ERROR.DB, err.toString())
  })


})

module.exports = router;
